import minium # 可以使用import直接导入整个minium包，不需要使用from minium import *
import time

class MiniProgramTest:

    def __init__(self):
        # 初始化 minitest 实例
        try:
            self.mini = minium.Minium({
                # 小程序包路径，windows路径需要使用r，或者换成/
                "project_path": r"E:\appData\wechattool\gold\GOLD_SALE_RE-sit-mp-weixin-2023-12-04_17-27-06\mp-weixin",
                # 微信开发者工具路径
                "dev_tool_path": r"D:\app\wechat_devtools\微信web开发者工具\cli.bat"
            })
            print("小程序连接成功")
        except Exception as e:
            print(f"小程序连接失败了: {e}")
            raise e

    def test_order(self):

        # 等待小程序启动完成，如果是在windows上已经启动，等待的时间可以少些，如果没有启动，这里设置大点
        time.sleep(2)
        page = self.mini.app.get_current_page()
        print(f"刷新页面:{page}")

        material_index,product_index,sku_index = self.product_order(0,0,0)
        while material_index != -1:
            material_index,product_index,sku_index = self.product_order(material_index,product_index,sku_index)


    # 由于微信小程序会出现崩溃，所以需要进行重试
    def product_order(self, material_index, product_index, sku_index):

        max_retries = 10  # 最大重试次数
        retry_count = 0

        if material_index >100 or product_index >100 or sku_index >100:
            return -1,-1,-1
        
        while retry_count < max_retries:
            try:
                # 检查连接状态
                if not self.mini or not self.mini.app:
                    print("重新初始化小程序连接...")
                    self.__init__()  # 重新初始化连接
                    time.sleep(3)  # 等待连接建立
                
                # 原有的代码逻辑
                self.mini.app.switch_tab("/pages/home/page")
                time.sleep(2)
                page = self.mini.app.get_current_page()
                
                # 点击材质，class="j-tab-item data-v-bf3f52c4"，默认激活的时候，class="j-tab-item data-v-bf3f52c4 active"
                material_elements = page.get_elements('.j-tab-item.data-v-bf3f52c4')
                if len(material_elements) <= material_index:
                    print("已经点击过所有材质")
                    material_index=-1
                    return material_index,product_index,sku_index
                
                if material_elements and len(material_elements) > material_index:
                    # click()方法在minium中是tap()方法
                    material_elements[material_index].click()
                    print(f"点击第{material_index}个材质分类")
                    time.sleep(2)
                    page = self.mini.app.get_current_page()
                else:
                    print("没有找到材质分类")

                # 3. 点击第一个产品购买，class="j-button data-v-4e769dff j-button-circle j-button-sm j-button-primary"
                product_elements = page.get_elements('.j-button.data-v-4e769dff.j-button-circle.j-button-sm.j-button-primary')
                
                if len(product_elements) <= product_index:
                    material_index+=1
                    product_index=0
                    sku_index=0
                    return material_index,product_index,sku_index
                
                if product_elements and len(product_elements) > 0:
                    product_elements[product_index].tap()
                    print(f"点击第{product_index}个产品购买")
                    time.sleep(2)
                    page = self.mini.app.get_current_page()
                else:
                    print("没有找到产品购买")

                # j-button data-v-4e769dff j-button-circle j-button-lg j-button-primary
                buy_element = page.get_element('.j-button.data-v-4e769dff.j-button-circle.j-button-lg.j-button-primary')
                if buy_element:
                    buy_element.click()
                    print("点击购买")
                    time.sleep(2)
                    page = self.mini.app.get_current_page()
                # sku-selector-option f-center data-v-49549432
                sku_elements = page.get_elements('.sku-selector-option.f-center.data-v-49549432')
                if len(sku_elements) <= sku_index:
                    product_index+=1
                    sku_index=0
                    return material_index,product_index,sku_index
                
                if sku_elements and len(sku_elements) > sku_index:
                    sku_elements[sku_index].click()
                    print(f"点击第{sku_index}个SKU")
                    time.sleep(2)
                    page = self.mini.app.get_current_page()
                # 购买j-button data-v-4e769dff j-button-circle j-button-lg j-button-primary
                buy_element = page.get_element('.j-button.data-v-4e769dff.j-button-circle.j-button-lg.j-button-primary')
                if buy_element:
                    buy_element.click()
                    print("点击购买")
                    time.sleep(4)
                    page = self.mini.app.get_current_page()
                # 自提 order-delivery-tab-item f-center data-v-e2b6cb98，无需处理
                # self_delivery_elements  = page.get_elements('.order-delivery-tab-item.f-center.data-v-e2b6cb98')
                # if self_delivery_elements and len(self_delivery_elements) > 0:
                #     self_delivery_elements[1].click()
                #     print("点击自提")
                #     time.sleep(2)
                #     page = self.mini.app.get_current_page()
                # 同意下单协议 iconfont picker iconfont-circle data-v-edc27f62
                agree_element = page.get_element('.iconfont.picker.iconfont-circle.data-v-edc27f62')
                if agree_element:
                    agree_element.click()
                    print("点击同意下单协议")
                    time.sleep(2)
                    page = self.mini.app.get_current_page()
                # 提交订单 j-button data-v-4e769dff j-button-lg j-button-primary
                submit_element = page.get_element('.j-button.data-v-4e769dff.j-button-lg.j-button-primary')
                if submit_element:
                    submit_element.click()
                    print("点击提交订单")
                    sku_index+=1
                    time.sleep(2)
                # 回退 iconfont iconfont-arrow-right data-v-edc27f62
                back_element = page.get_element('.iconfont.iconfont-arrow-right.data-v-edc27f62')
                if back_element:
                    back_element.click()
                    print("点击回退")
                    time.sleep(2)
                    page = self.mini.app.get_current_page()
                return material_index,product_index,sku_index
            except Exception as e:
                retry_count += 1
                print(f"第 {retry_count} 次尝试失败: {str(e)}")
                if retry_count >= max_retries:
                    print("达到最大重试次数，操作失败")
                    raise  # 重新抛出异常
                time.sleep(2)  # 重试前等待
                
                # 尝试重新初始化连接
                try:
                    self.mini.shutdown()  # 关闭现有连接
                except:
                    pass
                self.__init__()  # 重新初始化

    # 关闭小程序
    def teardown_class(self):
        try:
            self.mini.shutdown()
            print("小程序已关闭")
        except Exception as e:
            print(f"关闭小程序失败: {e}")
            
# 为了方便测试，这里直接运行
if __name__ == "__main__":
    t = MiniProgramTest()
    t.test_order()
